<?php

class Admin_ProductController extends Zend_Controller_Action
{
	private $_params;
	private $_auth;	
    public function init(){
        $this->_params      = $this->_request->getParams();        
        $this->_auth         = new My_Auth();
        $this->view->auth    = $this->_auth;        
        $this->_auth        = $this->_auth->checkAuthentication();
        $this->view->auth   = $this->_auth;
    }
    public function indexAction(){
        $modelP  = new Admin_Model_Product();                        
        $productList   = $modelP->getAllDataOnRun(array('wait'=>2))->toArray();        
        $this->view->productList = $productList;                        
    }
     public function expiredvipAction(){
        $modelP = new Admin_Model_Product();
        $modelU = new Admin_Model_User();                                
        $productList = $modelP->getAllData(array('wait'=>2,'type'=>'vi','time'=>time()))->toArray();
        $this->view->productList = $productList;    
        if ($this->getRequest()->isPost()) {            
            $formData = $this->getRequest()->getPost();            
            if($formData['proId']){
                $website= new Zend_Config_Ini(CONFIG_PATH.'/website.ini', APPLICATION_ENV);                                
                foreach($formData['proId'] as $o){                    
                    $modelP->updateWait($o,array('status'=>3));
                    //Thông báo tin hết hạn
                    $product = $modelP->getDataById($o);                                         
                    $owner = $modelU->getDataById($product['userId']);                    
                    $sender = $website->website->gmail;
                    $pwd = $website->website->gmailpw;                    
                    $receiver = $owner['email'];
                    $content = $website->website->expiredvip;
                    //My_Gmailsender::gsend($sender,$pwd,$receiver,'hello','hello','hello');
                }
                $this->_helper->redirector('expiredvip', 'product', 'admin');
                $this->view->mess ="Đã đổi trạng thái tin và gửi mail thông báo cho người dùng";
                $this->view->flag = "success";                
            }
            else{
                $this->view->mess ="Có tin nào đâu mà gửi";
                $this->view->flag = "alert";
            }
         }
    }
    public function expiredAction(){
        $modelProduct  = new Admin_Model_Product();                        
        $productList   = $modelProduct->getAllData(array('wait'=>2,'type'=>'no','time'=>time()))->toArray();
        $this->view->productList = $productList;    
         if ($this->getRequest()->isPost()) {            
            $formData = $this->getRequest()->getPost();            
            if($formData['proId']){
                foreach($formData['proId'] as $pro){
                    $pro = $modelProduct->getDataById($pro);
                    $photo = json_decode($pro['photo']);
                    foreach($photo as $o){            
                        unlink(WEB_PATH.$o);
                    }                                        
                    $modelProduct->deleteData($pro['id']);
                }
                $this->view->mess ="Đã xóa tất cả";
                $this->view->flag = "success";
                $this->_helper->redirector('expired', 'product', 'admin');
            }
            else{
                $this->view->mess ="Có tin nào đâu mà xóa";
                $this->view->flag = "alert";
            }
         }
    }
    public function detailAction(){
        $id = $this->_getParam('id', 0);        
        $modelP = new Admin_Model_Product();
        $modleU = new Admin_Model_User();        
        $proCheck = $modelP->getDataById($id);
        $userCheck = $modleU->getDataById($proCheck['userId']);                         
        if($proCheck){
            $proCheck['createDate'] = date('Y-m-d H:i',$proCheck['createDate']);
            $proCheck['startDate'] = date('Y-m-d H:i',$proCheck['startDate']);
            $proCheck['endDate'] = date('Y-m-d H:i',$proCheck['endDate']);
            $this->view->userCheck = $userCheck;
            $this->view->proCheck = $proCheck;                        
        }else{
            $this->_helper->redirector('index', 'product', 'admin');
        }
    } 
    public function deletevipAction(){
        $id = $this->_getParam('id', 0);   
        $modelPro = new Admin_Model_Product();
        $modelUser = new Admin_Model_User();
        $proCheck = $modelPro->getDataById($id)->toArray();
        $photo = json_decode($proCheck['photo']);        
        foreach($photo as $o){            
            unlink(WEB_PATH.$o);
        }        
        $userCheck = $modelUser->getDataById($proCheck['userId']);
        $modelUser->updateGold($userCheck['id'],array('gold'=>($userCheck['gold']+$proCheck['priceAd'])));        
        $modelPro->deleteData($id);
        $this->_helper->redirector('waitvip', 'product', 'admin');
    }
    public function deletewaitAction(){
        $id = $this->_getParam('id', 0);   
        $modelPro = new Admin_Model_Product();
        $proCheck = $modelPro->getDataById($id)->toArray();
        $photo = json_decode($proCheck['photo']);        
        foreach($photo as $o){            
            unlink(WEB_PATH.$o);
        }                        
        $modelPro->deleteData($id);
        $this->_helper->redirector('wait', 'product', 'admin');
    }
    public function editwaitAction(){
        $id = $this->_getParam('id', 0);        
        $modelPro = new Admin_Model_Product();
        $modelU = new Admin_Model_User();   
        $along= new Zend_Config_Ini(CONFIG_PATH.'/website.ini', APPLICATION_ENV);                             
        $proCheck = $modelPro->getDataById($id);
        $userCheck = $modelU->getDataById($proCheck['userId']); 
        $this->view->proCheck = $proCheck;
        $this->view->userCheck = $userCheck;
        if ($this->getRequest()->isPost()) {            
            $formData = $this->getRequest()->getPost(); 
            $dataUpdate=array();
            if($formData['title'] || $formData['content']){
                $dataUpdate['status']=2;
                $dataUpdate['startDate']=time();
                if(!$along->website->freedate || is_numeric($along->website->freedate)){
                    $dataUpdate['endDate']=time()+(86400*($along->website->freedate));
                }
                else{
                    $this->view->mess ="Vui lòng kiểm tra lại file website.ini";
                    $this->view->flag = "alert";
                    return;
                }
                $dataUpdate['title']=$formData['title'];
                $dataUpdate['content']=$formData['content'];
                $dataUpdate['viewer']=$this->_auth['adminId'];
                $modelU->inceaseQty($userCheck['id'],$userCheck['qty']+1);                
                $modelPro->updateWait($id, $dataUpdate);
                $this->_helper->redirector('wait', 'product', 'admin');
            }
            else{
                $this->view->mess ="Vui lòng điền đầy đủ dữ liệu";
                $this->view->flag = "alert";
            }
        }
    }     
     public function editvipAction(){
        $id = $this->_getParam('id', 0);        
        $modelP = new Admin_Model_Product();
        $modelU = new Admin_Model_User();        
        $proCheck = $modelP->getDataById($id);
        $userCheck = $modelU->getDataById($proCheck['userId']); 
        $this->view->proCheck = $proCheck;
        $this->view->userCheck = $userCheck;
        if ($this->getRequest()->isPost()) {            
            $formData = $this->getRequest()->getPost();             
            $dataUpdate=array();
            if($formData['title'] || $formData['content']||$formData['startDate'] || $formData['endDate']){            
                if($formData['endDate']<$formData['startDate']){                 
                    $this->view->mess ="Ngày bắt đầu không được lớn hơn ngày kết thúc";
                    $this->view->flag = "alert";
                    return;
                }                
                $dataUpdate['status']=2;
                $along=strtotime($formData['endDate'])-strtotime($formData['startDate']);
                $dataUpdate['startDate']=time();
                $dataUpdate['endDate']= time()+$along;
                $dataUpdate['title']=$formData['title'];
                $dataUpdate['shortTitle']=$this->_helper->setup($formData['title']);
                $dataUpdate['content']=$formData['content'];
                $dataUpdate['viewer']=$this->_auth['adminId'];
                $modelP->updateWait($id, $dataUpdate);
                $modelU->inceaseQty($userCheck['id'],$userCheck['qty']+1);                
                //Thông báo tin đã được duyệt
                $modelM = new Admin_Model_Mail();
                $modelA = new Admin_Model_Admin();
                $viewer = $modelA->getDataById($this->_auth['adminId'])->toArray();                
                $link = '<a href="'.BASE_URL1.'/chi-tiet/p'.$proCheck['id'].'-'.$proCheck['shortTitle'].'">tại đây</a>';                
                $startS = new DateTime(date("Y-m-d H:i",$proCheck['startDate']));
                $endS = new DateTime(date("Y-m-d H:i",$proCheck['endDate']));                
                $endT = new DateTime(date("Y-m-d H:i",$dataUpdate['endDate']));
                $numDate = (int)$endS->diff($startS)->days+1;
                $end = new DateTime(date("y-m-d H:i",$dataUpdate['startDate'] + ($numDate*60*60*24)));
                $bonus = ($end->diff($endT)->d)*24+($end->diff($endT)->h).' giờ';
                $startDate = date("H",$dataUpdate['startDate']).' Giờ '.date("i",$dataUpdate['startDate']).' Phút - Ngày '.date("d",$dataUpdate['startDate']).' Tháng '.date("m",$dataUpdate['startDate']).' Năm '.date("Y",$dataUpdate['startDate']);
                $endDate = date("H",$dataUpdate['endDate']).' Giờ '.date("i",$dataUpdate['endDate']).' Phút - Ngày '.date("d",$dataUpdate['endDate']).' Tháng '.date("m",$dataUpdate['endDate']).' Năm '.date("Y",$dataUpdate['endDate']);
                                                                           
                $mailDetail = $modelM->getDataId('informVip')->toArray();
                $mailDetail['content'] = str_replace('[emanlluf]',$userCheck['fullname'],$mailDetail['content']);                 
                $mailDetail['content'] = str_replace('[knil]',$link,$mailDetail['content']);
                $mailDetail['content'] = str_replace('[eltit]',$formData['title'],$mailDetail['content']);
                $mailDetail['content'] = str_replace('[etaDtrats]',$startDate,$mailDetail['content']);
                $mailDetail['content'] = str_replace('[etaDdne]',$endDate,$mailDetail['content']);
                $mailDetail['content'] = str_replace('[dAecirp]',number_format($proCheck['priceAd'],0,'.',','),$mailDetail['content']);
                $mailDetail['content'] = str_replace('[etaDsunob]',$bonus,$mailDetail['content']);
                $mailDetail['content'] = str_replace('[reweiv]',$viewer['fullname'],$mailDetail['content']);
                                
                $website= new Zend_Config_Ini(CONFIG_PATH.'/website.ini', APPLICATION_ENV);
                $subject = $mailDetail['subject'];                    
                $name = $mailDetail['name'];
                $sender = $website->website->gmail;
                $pwd = $website->website->gmailpw;                    
                $receiver = $userCheck['email'];
                $content = $mailDetail['content'];                    
                My_Gmailsender::gsend($sender,$pwd,$receiver,$subject,$name,$content);
                                                                    
                $this->_helper->redirector('waitvip', 'product', 'admin');
            }
            else{
                $this->view->mess ="Vui lòng điền đầy đủ dữ liệu";
                $this->view->flag = "alert";
            }
        }
    }
    public function waitvipAction(){
        $modelProduct  = new Admin_Model_Product();                
        $productList   = $modelProduct->getAllData(array('wait'=>1, 'type'=>'vi'))->toArray();        
        $this->view->productList = $productList;  
    }
    public function waitAction(){
        $modelProduct  = new Admin_Model_Product();                
        $productList   = $modelProduct->getAllData(array('wait'=>1, 'type'=>'no'))->toArray();        
        $this->view->productList = $productList;  
    }
    public function deleteAction(){
        $id = $this->_getParam('id', 0);
        $modelPro = new Admin_Model_Product();        
        $proCheck = $modelPro->getDataById($id);
        if($proCheck){
            $this->view->proCheck = $proCheck;            
            if($this->getRequest()->isPost()){
                $del = $this->getRequest()->getPost('del');
                if($del == 'Có'){ 
                    $photo = json_decode($proCheck['photo']);        
                    foreach($photo as $o){            
                        unlink(WEB_PATH.$o);
                    } 
                    $modelPro->deleteData($id);                                       
                }
                $this->_helper->redirector('index', 'product', 'admin');
            }
        }else{
            $this->_helper->redirector('index', 'product', 'admin');
        }        
    }
    public function addAction(){        
        $form = new Admin_Form_Product();        
        $form->submit->setLabel('Thêm mới');
        $this->view->form = $form;                        
        if ($this->getRequest()->isPost()) {            
            $formData = $this->getRequest()->getPost();            
            if ($form->isValid($formData)) {                
                $addData['title']       = $form->getValue('title');                
                $addData['shortTitle']  = $this->_helper->setup($form->getValue('title'));
                $addData['createDate']  = strtotime($form->getValue('createDate'));                                                
                $addData['startDate']   = strtotime($form->getValue('startDate'));
                $addData['endDate']     = strtotime($form->getValue('endDate'));                
                $addData['content']     = $form->getValue('content');
                $addData['price']       = $form->getValue('price');
                $addData['human']       = $form->getValue('human');
                $addData['itemId']      = $form->getValue('itemId');
                $addData['areaId']      = $form->getValue('areaId');
                $addData['transaction'] = $form->getValue('transaction');
                $addData['userId']      = $form->getValue('userId');                                            
                $addData['status']      = $form->getValue('status');
                $addData['type']        = $form->getValue('type');
                $addData['contact']     = $form->getValue('contact');
                $addData['mobile']      = $form->getValue('mobile');
                $addData['emailCont']   = $form->getValue('emailCont');
                $addData['addressCont'] = $form->getValue('addressCont');
                $addData['priceAd']     = $form->getValue('priceAd');                
                $modelProduct = new Admin_Model_Product();
                if($addData['type'] == 'no'){
                    $upload = new Zend_File_Transfer();                
                    $files = $upload->getFileInfo();
                    $i=1;                                                                                
                    foreach($files as $f){
                        $upload = new Zend_File_Transfer(); 
                        $upload->setDestination(PUBLIC_PATH.'/upload/product/');
                        if($f['name']){                        
                            $fileName = time().'_'.$i++.'_'.$f['name'];                            
                            $upload->addFilter('Rename',$fileName);
                            $upload->receive($f['name']);
                            $addData['photo'][] = $fileName;                           
                        }                    
                    } 
                    $addData['priceAd'] = '';  
                }else{                    
                    $modelUser = new Admin_Model_User();                
                    $u = $modelUser->getDataById($addData['userId']);
                    $modelUser->inceaseQty($u['id'],$u['qty']+1);                   //Tăng số bài đăng cho User                                  
                    $num = $u['qty']+1;                    
                                                                              
                    $upload = new Zend_File_Transfer();                
                    $files = $upload->getFileInfo();
                    $i=1;                                                                                
                    foreach($files as $f){
                        $upload = new Zend_File_Transfer(); 
                        $upload->setDestination(PUBLIC_PATH.'/upload/product/');
                        if($f['name']){                        
                            $fileName = $addData['userId'].'_'.$num.'_'.$i++.'.'.My_Service_File::getExtension($f['name']);
                            $upload->addFilter('Rename',$fileName);
                            $upload->receive($f['name']);
                            $addData['photo'][] = $fileName;                           
                        }                    
                    }   
                    $configPrice = new Zend_Config_Ini(CONFIG_PATH.'/price.ini', APPLICATION_ENV);
                    $price=$configPrice->price->toArray();                  
                    $start = new DateTime($form->getValue('startDate'));
                    $end = new DateTime($form->getValue('endDate'));                                                            
                    $addData['priceAd'] = ((int)$end->diff($start)->d+1)*$price['price'];
                    //Trừ phí đăng tin của User (không được thực hiện ở trang admin)                                                                                                                                     
                }                                                                                                                                                                                                                                                         
                $addData['photo'] = json_encode($addData['photo']);
                //pr($addData);
                $addId = $modelProduct->addData($addData);                
                if($addId){
                    $this->_helper->redirector('index', 'product', 'admin');
                }else{
                    $this->view->mess ="Đã có lỗi xảy ra";
                    $this->view->flag = "alert";
                }                				
            }else{
                $form->populate($formData);
            }
        }
    }
    public function editAction(){
		$form = new Admin_Form_Product();
		$form->submit->setLabel('Lưu thay đổi');
		$this->view->form = $form;
        
        $dataUpdate['id'] = (int)($this->_getParam('id', 0));                
        $modelPro = new Admin_Model_Product();
		$proCheck = $modelPro->getDataById($dataUpdate['id']);        
		if($this->getRequest()->isPost()){
			$formData = $this->getRequest()->getPost();
			if ($form->isValid($formData)){
                
                $updateData['id']           = $form->getValue('id');
				$updateData['title']       = $form->getValue('title');                
                $updateData['shortTitle']  = $this->_helper->setup($form->getValue('title'));
                $updateData['createDate']  = strtotime($form->getValue('createDate'));
                $updateData['startDate']   = strtotime($form->getValue('startDate'));
                $updateData['endDate']     = strtotime($form->getValue('endDate'));
                $updateData['content']     = $form->getValue('content');
                $updateData['price']     = $form->getValue('price');
                $updateData['human']       = $form->getValue('human');
                $updateData['itemId']       = $form->getValue('itemId');
                $updateData['areaId']       = $form->getValue('areaId');
                $updateData['transaction'] = $form->getValue('transaction');
                $updateData['userId']      = $form->getValue('userId');                                            
                $updateData['status']      = $form->getValue('status');
                $updateData['type']      = $form->getValue('type');
                $updateData['contact']      = $form->getValue('contact');
                $updateData['mobile']      = $form->getValue('mobile');
                $updateData['emailCont']      = $form->getValue('emailCont');
                $updateData['addressCont']      = $form->getValue('addressCont');
                $updateData['priceAd']      = $form->getValue('priceAd');                
                $modelProduct = new Admin_Model_Product();
                if($updateData['type'] == 'no'){
                    $upload = new Zend_File_Transfer();                
                    $files = $upload->getFileInfo();
                    $i=0;                                                                                                                                           
                    foreach($files as $f){
                        if($f['name']){
                            $upload = new Zend_File_Transfer(); 
                            $upload->setDestination(PUBLIC_PATH.'/upload/product/');                                                    
                            $fileName = $updateData['id'].'_'.time().'_'.++$i.'.'.My_Service_File::getExtension($f['name']);                            
                            $upload->addFilter('Rename',$fileName);
                            $upload->receive($f['name']);
                            $updateData['photo'][] = $fileName;
                        }else
                            break;                                                                                                           
                    }                    
                    if($i>0){                                                
                        foreach(json_decode($proCheck['photo']) as $v){
                            unlink(WEB_PATH.$v);
                        }
                    }                     
                    $updateData['priceAd'] = '';
                }else{                                                                                            
                    $upload = new Zend_File_Transfer();                
                    $files = $upload->getFileInfo();
                    $i=0;                                                                                
                    foreach($files as $f){
                        $upload = new Zend_File_Transfer(); 
                        $upload->setDestination(PUBLIC_PATH.'/upload/product/');
                        if($f['name']){                        
                            $fileName = $updateData['id'].'_'.time().'_'.++$i.'.'.My_Service_File::getExtension($f['name']);
                            $upload->addFilter('Rename',$fileName);
                            $upload->receive($f['name']);
                            $updateData['photo'][] = $fileName;                           
                        }else
                            break;                    
                    }                       
                    $configPrice = new Zend_Config_Ini(CONFIG_PATH.'/price.ini', APPLICATION_ENV);
                    $price=$configPrice->price->toArray();                  
                    $start = new DateTime($form->getValue('startDate'));
                    $end = new DateTime($form->getValue('endDate'));                                                            
                    $updateData['priceAd'] = ((int)$end->diff($start)->d+1)*$price['price'];
                }    
                if(!isset( $updateData['photo']))
                    $updateData['photo'] = $proCheck['photo'];
                else
                    $updateData['photo'] = json_encode($updateData['photo']);
                                         
                $modelProduct->updateData($updateData['id'],$updateData);
                $this->_helper->redirector('index', 'product', 'admin');
			}else{
				$form->populate($formData);
			}
		}else{			            
            if($proCheck){;                                 
                $proCheck['createDate'] = date('Y-m-d H:i',$proCheck['createDate']);
                $proCheck['startDate'] = date('Y-m-d H:i',$proCheck['startDate']);
                $proCheck['endDate'] = date('Y-m-d H:i',$proCheck['endDate']);
                $this->view->proCheck= $proCheck->toArray();
                //pr($proCheck);
    			$form->populate($proCheck->toArray());                
            }else{
                $this->_helper->redirector('index', 'admin', 'admin');
            }
		}
    }
    public function cleanupAction(){
        $modelProduct = new Admin_Model_Product();
        $cleanData = $modelProduct->getAllDataMess();
        if($cleanData){
            $cleanData = $cleanData->toArray(); 
            foreach($cleanData as $o){
                $o['photo'] = json_decode($o['photo']);
                if(isset($o['photo']) || $o['photo']!=null){
                    foreach($o['photo'] as $i){
                        unlink(WEB_PATH.$i);
                    }
                }
                $modelProduct->deleteData($o['id']);                                            
            }
        }
        $this->_helper->layout()->disableLayout(true);
        $this->_helper->viewRenderer->setNoRender(true);           
    }
    
}